var app = angular.module('fiveApp');
app.controller('formCtr', ['$rootScope', '$scope', 'ajaxService', '$stateParams', function ($rootScope, $scope, ajax, $stateParams) {

    $scope.data = {
        type: ['年报', '注销', '营业执照注册', '营业执照变更'],
        form: {type: 1, title: '', name: '', idcard: '', mobile: ''},
        result: {
            "title": "",
            "name": "",
            "type": "1",
            "idcard": "",
            "mobile": "",
            "price": 0,
            "order_sn": "",
            "openid": ""
        },
        step: 1, order_sn: ''
    };
    $scope.$on('$stateChangeSuccess', function () {
        var tempForm = JSON.parse(localStorage.getItem('tempForm'));
        if (tempForm) $scope.data.form = tempForm;

        $scope.data.form.type = parseInt($stateParams.query);

        if ($scope.data.form.type < 1 || $scope.data.form.type > 4) $scope.data.form.type = 1

        if ($scope.data.form.type == 1 && window._year > 0) {
            $scope.data.step = 4
        } else if ($scope.data.form.type == 2 && window._exit > 0) {
            $scope.data.step = 4
        } else if ($scope.data.form.type == 3 && window._register > 0) {
            $scope.data.step = 4
        } else if ($scope.data.form.type == 4 && window._change > 0) {
            $scope.data.step = 4
        }
        if ($scope.data.step == 4) {
            $scope.getOrderOne($scope.data.form.type)
        }

    })
    $scope.getOrderOne = function (type) {
        ajax('indexGetOrderOne', {type: type}, function (res) {
            if (!res.errCode && res.data) {
                $scope.data.order_sn = res.data.order_sn
            }
        })
    }
    $scope.$on('$destroy', function () {
        localStorage.setItem('tempForm', JSON.stringify($scope.data.form))
    })
    $scope.submit = function () {
        ajax('indexCreate', $scope.data.form, function (res) {
            if (!res.errCode) {
                $scope.data.result = res.data
                $scope.data.step = 2
            }
        })
    }
    $scope.pay = function () {
        ajax('indexPayParams', {order_sn: $scope.data.result.order_sn}, function (res) {
            if (!res.errCode) {
                WeixinJSBridge.invoke('getBrandWCPayRequest', JSON.parse(res.data), function (res) {
                    if (res.err_msg == 'get_brand_wcpay_request:ok') {
                        $.iBox.success('支付成功')
                        $scope.$apply(function () {
                            $scope.data.order_sn = $scope.data.result.order_sn
                            $scope.data.step = 3;
                        })
                        if ($scope.data.form.type > 1) {
                            return  $scope.location('/upload/index/' + $scope.data.result.order_sn)
                        }
                    }
                });
            }
        })
    }

}
])